package com.youedata.modular.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ZipUtil;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.youedata.base.consts.ConstantsContext;
import com.youedata.util.FastDFSKit;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Map;

/**
 * 文件上传管理控制器
 *
 * @author hao.yan
 * @date 2020-07-30 21:30:31
 */
@RestController
@Api(value = "/fastDFS", tags = "文件上传管理控制器")
@RequestMapping("/fastDFS")
@Slf4j
public class FastDFSController {

    @Autowired
    private FastDFSKit fastDFSKit;

    /**
     * 上传文件
     *
     * @author hao.yan
     * @date 2020-07-30
     */
    @ResponseBody
    @PostMapping("/upload")
    @ApiOperation(value = "上传并返回完整访问地址")
    public ResponseData upload(MultipartFile file) throws IOException {
        return ResponseData.success(fastDFSKit.uploadFile(file));
    }

    /**
     * 上传图片且生成缩略图
     *
     * @author hao.yan
     * @date 2020-07-30
     */
    @ResponseBody
    @PostMapping("/uploadImg")
    @ApiOperation(value = "上传图片且生成缩略图并返回完整访问地址")
    public ResponseData uploadImg(MultipartFile file) throws IOException {
        return ResponseData.success(fastDFSKit.uploadImageAndCrtThumbImage(file));
    }

    /**
     * 上传指定尺寸缩略图
     *
     * @author hao.yan
     * @date 2020-07-30
     */
    @ResponseBody
    @PostMapping("/uploadImageThumbnail")
    @ApiOperation(value = "上传图片且生成缩略图并返回完整访问地址")
    public ResponseData uploadImageThumbnail(MultipartFile file, int width, int height) throws IOException {
        return ResponseData.success(fastDFSKit.uploadImageThumbnail(file, width, height));
    }

    /**
     * 文件下载
     *
     * @author hao.yan
     * @date 2020-07-30
     */
    @GetMapping("/download")
    @ApiOperation(value = "下载文件")
    public ResponseEntity<InputStreamResource> download(@ApiParam String fileUrl, @ApiParam String fileName, HttpServletResponse response) {

        byte[] data = fastDFSKit.download(fileUrl);

        InputStreamResource resource = new InputStreamResource(new ByteArrayInputStream(data));
        String dfileName = null;
        try {
            dfileName = new String(fileName.getBytes("gb2312"), "iso8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", dfileName);
        return new ResponseEntity<>(resource, headers, HttpStatus.CREATED);
    }


    /**
     * 文件批量下载
     *
     * @author hao.yan
     * @date 2020-07-30
     */
    @GetMapping("/downloadZip")
    @ApiOperation(value = "文件批量下载")
    public ResponseEntity<InputStreamResource> downloadZip(@ApiParam String fileUrls, @ApiParam String fileNames, @ApiParam String type, HttpServletResponse response) {
        String[] urls = fileUrls.split(",");
        String[] names = fileNames.split(",");

        String dir = ConstantsContext.getFileUploadPath() + File.separator + IdWorker.get32UUID();

        // 创建临时文件
        for (int i = 0; i < urls.length; i++) {
            byte[] data = fastDFSKit.download(urls[i]);
            File file = FileUtil.writeBytes(data, dir + File.separator + names[i]);
        }

        //打包下载
        File zip = ZipUtil.zip(dir);
        return FastDFSKit.renderFile(type + new SimpleDateFormat("yyyyMMddHHmmss").format(DateTime.now()) + ".zip", zip.getAbsolutePath());
    }

    /**
     * UEditor图片上传
     *
     * @author hao.yan
     * @Date 2019/8/26 15:19
     */
    @RequestMapping(value = "/ueditor/upload")
    @ResponseBody
    public Map imgUpdate(MultipartFile upfile) throws IOException {
        return fastDFSKit.ueditorUploadFile(upfile);
    }


    /**
     * 上传指定尺寸缩略图
     *
     * @author hao.yan
     * @date 2020-07-30
     */
    @RequestMapping(value = "/ueditor/uploadImageThumbnail")
    @ResponseBody
    public Map ueditorUploadFileSize(MultipartFile upfile) throws IOException {
        return fastDFSKit.ueditorUploadFileSize(upfile,320,150);
    }
}

